<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">易耗品计划</h2>
      <button @click="$router.push('/consumable-plan/form')" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
        <PlusIcon class="h-5 w-5 mr-2" />
        创建计划
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <form @submit.prevent="handleSearch" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="semester" class="block text-sm font-medium text-gray-700">学期</label>
          <select id="semester" v-model="searchForm.semester" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择学期</option>
            <option value="2024-1">2024年春季学期</option>
            <option value="2024-2">2024年秋季学期</option>
            <option value="2025-1">2025年春季学期</option>
            <option value="2025-2">2025年秋季学期</option>
          </select>
        </div>
        <div>
          <label for="laboratory" class="block text-sm font-medium text-gray-700">实验室</label>
          <select id="laboratory" v-model="searchForm.laboratoryId" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择实验室</option>
            <option value="1">计算机实验室</option>
            <option value="2">物理实验室</option>
            <option value="3">化学实验室</option>
            <option value="4">生物实验室</option>
          </select>
        </div>
        <div>
          <label for="status" class="block text-sm font-medium text-gray-700">状态</label>
          <select id="status" v-model="searchForm.status" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择状态</option>
            <option value="DRAFT">草稿</option>
            <option value="SUBMITTED">已提交</option>
            <option value="APPROVED">已批准</option>
            <option value="REJECTED">已拒绝</option>
          </select>
        </div>
        <div>
          <label for="createDate" class="block text-sm font-medium text-gray-700">创建日期</label>
          <input type="date" id="createDate" v-model="searchForm.createDate" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div class="md:col-span-4 flex justify-end space-x-3 mt-4">
          <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">搜索</button>
          <button type="button" @click="handleReset" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">重置</button>
        </div>
      </form>
    </div>

    <!-- 计划列表 -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <div v-if="loading" class="text-center py-8">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>
      <div v-else class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学期</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实验室</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">计划项目数</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">预算总额</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="plan in plans" :key="plan.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ plan.semester }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ plan.laboratory }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ plan.itemCount }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥{{ plan.totalBudget.toLocaleString() }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', getStatusClass(plan.status)]">
                  {{ getStatusText(plan.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ plan.createTime }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewDetail(plan)" class="text-indigo-600 hover:text-indigo-900 mr-3">查看</button>
                <button @click="editPlan(plan)" v-if="plan.status === 'DRAFT'" class="text-indigo-600 hover:text-indigo-900 mr-3">编辑</button>
                <button @click="submitPlan(plan)" v-if="plan.status === 'DRAFT'" class="text-green-600 hover:text-green-900 mr-3">提交</button>
                <button @click="approvePlan(plan)" v-if="plan.status === 'SUBMITTED'" class="text-green-600 hover:text-green-900">审批</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="flex justify-end mt-6">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <button @click="handleCurrentChange(pagination.current - 1)" :disabled="pagination.current === 1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Previous</span>
            <ChevronLeftIcon class="h-5 w-5" aria-hidden="true" />
          </button>
          <button v-for="page in totalPages" :key="page" @click="handleCurrentChange(page)" :class="['relative inline-flex items-center px-4 py-2 border text-sm font-medium', page === pagination.current ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50']">
            {{ page }}
          </button>
          <button @click="handleCurrentChange(pagination.current + 1)" :disabled="pagination.current === totalPages" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Next</span>
            <ChevronRightIcon class="h-5 w-5" aria-hidden="true" />
          </button>
        </nav>
        <div class="ml-4 flex items-center text-sm text-gray-700">
          <span>共 {{ pagination.total }} 条</span>
          <select v-model="pagination.size" @change="handleSizeChange($event.target.value)" class="ml-2 block w-auto pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
            <option :value="10">10 条/页</option>
            <option :value="20">20 条/页</option>
            <option :value="50">50 条/页</option>
            <option :value="100">100 条/页</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="mt-8 grid grid-cols-1 md:grid-cols-4 gap-6">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <DocumentTextIcon class="h-8 w-8 text-blue-500" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总计划数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ totalPlans }}</p>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <CheckCircleIcon class="h-8 w-8 text-green-500" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">已批准计划</p>
            <p class="text-2xl font-semibold text-gray-900">{{ approvedPlans }}</p>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <ClockIcon class="h-8 w-8 text-yellow-500" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">待审批计划</p>
            <p class="text-2xl font-semibold text-gray-900">{{ pendingPlans }}</p>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <CurrencyDollarIcon class="h-8 w-8 text-indigo-500" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总预算</p>
            <p class="text-2xl font-semibold text-gray-900">¥{{ totalBudget.toLocaleString() }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  PlusIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  DocumentTextIcon,
  CheckCircleIcon,
  ClockIcon,
  CurrencyDollarIcon,
} from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const router = useRouter()

const plans = ref([])
const loading = ref(false)

const searchForm = reactive({
  semester: '',
  laboratoryId: '',
  status: '',
  createDate: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const totalPages = computed(() => Math.ceil(pagination.total / pagination.size))

// 计算统计信息
const totalPlans = computed(() => plans.value.length)
const approvedPlans = computed(() => plans.value.filter(plan => plan.status === 'APPROVED').length)
const pendingPlans = computed(() => plans.value.filter(plan => plan.status === 'SUBMITTED').length)
const totalBudget = computed(() => plans.value.reduce((sum, plan) => sum + plan.totalBudget, 0))

// 获取状态样式
const getStatusClass = (status) => {
  const statusMap = {
    'DRAFT': 'bg-gray-100 text-gray-800',
    'SUBMITTED': 'bg-yellow-100 text-yellow-800',
    'APPROVED': 'bg-green-100 text-green-800',
    'REJECTED': 'bg-red-100 text-red-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'DRAFT': '草稿',
    'SUBMITTED': '已提交',
    'APPROVED': '已批准',
    'REJECTED': '已拒绝'
  }
  return statusMap[status] || status
}

// 查看详情
const viewDetail = (plan) => {
  router.push(`/consumable-plan/detail/${plan.id}`)
}

// 编辑计划
const editPlan = (plan) => {
  router.push(`/consumable-plan/form/${plan.id}`)
}

// 提交计划
const submitPlan = async (plan) => {
  try {
    // 调用后端API提交计划
    await request.put(`/consumable-plans/${plan.id}/submit`)
    showMessage('计划提交成功', 'success')
    loadPlans()
  } catch (error) {
    console.error('提交计划失败:', error)
    showMessage('提交计划失败', 'error')
  }
}

// 审批计划
const approvePlan = (plan) => {
  router.push(`/consumable-plan/approval/${plan.id}`)
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadPlans()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    semester: '',
    laboratoryId: '',
    status: '',
    createDate: ''
  })
  pagination.current = 1
  loadPlans()
}

// 页面大小改变
const handleSizeChange = (size) => {
  pagination.size = parseInt(size)
  pagination.current = 1
  loadPlans()
}

// 当前页改变
const handleCurrentChange = (current) => {
  if (current < 1 || current > totalPages.value) return
  pagination.current = current
  loadPlans()
}

// 加载计划列表
const loadPlans = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }

    const response = await request.get('/consumable-plans/list', { params })
    plans.value = response.data.records.map(plan => ({
      id: plan.id,
      semester: plan.semester,
      laboratory: plan.laboratoryName,
      itemCount: plan.items ? plan.items.length : 0,
      totalBudget: plan.totalBudget,
      status: plan.status,
      createTime: plan.createTime
    }))
    pagination.total = response.data.total
    
  } catch (error) {
    console.error('加载计划列表失败:', error)
    showMessage('加载计划列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadPlans()
})
</script>